import React, { useEffect, useRef, useState } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, DatePicker, Input, Table, Typography } from 'antd';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

import Filter from '@/components/filter';

import { store } from '@/store';

import { usePermission } from '@/auth';
import {
  proDataCostWeekCalculate,
  proDataCostWeekList,
  proDataCostWeekSave
} from '@/services/bizApi/zhouchengbenqingkuangjiekou';

/** 该模块增删改查对象 */
export type BizObamountct = BIZAPI.ProDataCostWeekEntity;

const Page: React.FC = () => {
  const permission = usePermission();
  const [filter] = Filter.useForm();

  const [tableData, setTableData] = useState<BizObamountct[]>([]);

  const [weekRange, setWeekRange] = useState({
    startDate: null,
    endDate: null
  });
  const currentWeek = dayjs();
  //默认去年
  const currentYear = useRef(dayjs().subtract(1, 'year'));
  const table = useAntdTable(
    async () => {
      if (!weekRange.startDate || !weekRange.endDate) {
        return {
          list: [],
          total: 0
        };
      }
      const res = await proDataCostWeekList({
        startDate: weekRange.startDate!,
        endDate: weekRange.endDate!,
        year: currentYear.current.format('YYYY') as unknown as number
      });

      setTableData(res.data || []);

      return {
        list: res.data || [],
        total: res.data?.length || 0
      };
    },
    {
      form: filter
    }
  );

  const defaultColumns: ColumnsType<BizObamountct> = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      width: 50,
      fixed: 'left',
      render: (_, row, index) => index + 1
    },
    {
      title: '类别',
      dataIndex: 'category',
      fixed: 'left',
      align: 'center',
      width: 200
    },
    {
      title: '本周药剂吨水单耗目标(kg/吨)',
      dataIndex: 'drugTarget',
      width: 120,
      render: (value) => <Text>{value ? value : '--'}</Text>
    },
    {
      title: '本周药剂吨水单耗(kg/吨)',
      dataIndex: 'drugActual',
      width: 120,
      render: (value) => <Text>{value ? value : '--'}</Text>
    },
    {
      title: '本周对比目标药剂吨水(%)',
      dataIndex: 'drugVs',
      width: 120,
      render: (value) => (
        <Text style={{ color: value > 0 ? 'red' : '' }}>{value ? value : '--'}</Text>
      )
    },
    {
      title: '本周金额吨水单耗目标(元/吨)',
      dataIndex: 'amountTarget',
      width: 120
    },
    {
      title: '本周金额吨水单耗(元/吨)',
      dataIndex: 'amountActual',
      width: 120,
      render: (value) => <Text>{value ? `${value}` : '--'}</Text>
    },
    {
      title: '本周对比目标金额吨水(%)',
      dataIndex: 'amountVs',
      width: 120,
      render: (value) => (
        <Text style={{ color: value > 0 ? 'red' : '' }}>{value ? `${value}` : '--'}</Text>
      )
    },
    {
      title: (
        <>
          <div>本周对比{currentYear.current.format('YYYY')}年金额吨水(%)</div>
        </>
      ),
      dataIndex: 'amountActualVsYear',
      width: 120,
      render: (value) => <Text>{value ? value : '--'}</Text>
    },

    {
      title: '本周环比上周金额吨水(%)',
      dataIndex: 'amountActualWow',
      width: 120,
      render: (value) => <Text>{value ? value : '--'}</Text>
    },
    {
      title: '未完成原因',
      dataIndex: 'reason',
      ellipsis: true,
      render: (value: string, record: BizObamountct, index: number) => (
        <Input.TextArea
          defaultValue={record.reason}
          autoSize={{ minRows: 2, maxRows: 4 }}
          onBlur={(e) => {
            setTableData((prev) => {
              prev[index].reason = e.target.value as unknown as string;
              return [...prev];
            });
          }}
        />
      )
    }
  ];

  const onSearch = async () => {
    await proDataCostWeekCalculate({
      startDate: weekRange.startDate!,
      endDate: weekRange.endDate!,
      year: currentYear.current.format('YYYY') as unknown as number
    });
    table.loading = true;
    table.search.submit();
    table.loading = false;
  };

  const onReset = () => {
    table.search.reset();
  };

  const { Text } = Typography;

  // 处理周选择逻辑
  const handleWeekSelect = (date: any) => {
    if (!date) {
      setWeekRange({ startDate: null, endDate: null });
      return;
    }

    // 计算周开始日期（周一）
    const startDate = date.startOf('week');
    // 计算周结束日期（周日）
    const endDate = date.endOf('week');
    // 获取周数
    console.log(date.week());
    setWeekRange({
      startDate: startDate.format('YYYY-MM-DD'),
      endDate: endDate.format('YYYY-MM-DD')
    });

    setTimeout(() => {
      table.search.submit();
    }, 500);
  };

  useEffect(() => {
    handleWeekSelect(currentWeek);
  }, []);

  return (
    <>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() && (
              <Button
                onClick={async () => {
                  console.log(filter);
                  const query = tableData.map((item) => {
                    return {
                      ...item,
                      id: item.id
                    };
                  });
                  await proDataCostWeekSave(query as BIZAPI.ProDataCostWeekEntity[]);
                  store.app?.message.success('保存成功');
                  table.refresh();
                }}
                type="primary"
              >
                保存
              </Button>
            )}
          </>
        }
      >
        <Filter.Item name="week">
          <DatePicker
            picker="week"
            allowClear={false}
            format="YYYY-w周"
            defaultValue={currentWeek}
            onChange={handleWeekSelect}
            placeholder={'请选择周'}
          />
          <Text style={{ marginLeft: '20px' }}>
            周日期：{weekRange?.startDate} - {weekRange?.endDate}
          </Text>
        </Filter.Item>

        <Filter.Item name="year" style={{ marginLeft: '40px' }} label="对比年">
          <DatePicker
            picker="year"
            allowClear={false}
            format="YYYY"
            onChange={(_value: any) => {
              currentYear.current = dayjs(_value);
              table.search.submit();
            }}
            defaultValue={currentYear.current}
            placeholder={'请选择年'}
          />
        </Filter.Item>

        <Filter.Item>
          <Button htmlType="submit" type="primary" disabled={table.loading}>
            计算
          </Button>
        </Filter.Item>

        {/* <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item> */}
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObamountct>
        size="small"
        columns={defaultColumns as ColumnsType<BizObamountct>}
        // summary={(pageData) => {
        //   let totalDrugTarget = 0,
        //     totalDrugActual = 0,
        //     totalDrugVs = 0,
        //     totalAmountTarget = 0,
        //     totalAmountActual = 0,
        //     totalAmountVs = 0,
        //     totalAmountActualWow = 0;

        //   pageData.forEach(
        //     ({
        //       drugTarget,
        //       drugActual,
        //       drugVs,
        //       amountTarget,
        //       amountActual,
        //       amountVs,
        //       amountActualWow
        //     }) => {
        //       totalDrugTarget += Number(drugTarget);
        //       totalDrugActual += Number(drugActual);
        //       totalDrugVs += Number(drugVs);
        //       totalAmountTarget += Number(amountTarget);
        //       totalAmountActual += Number(amountActual);
        //       totalAmountVs += Number(amountVs);
        //       totalAmountActualWow += Number(amountActualWow);
        //     }
        //   );
        //   return (
        //     <>
        //       <Table.Summary.Row>
        //         <Table.Summary.Cell index={0}></Table.Summary.Cell>
        //         <Table.Summary.Cell index={1}>
        //           <div style={{ textAlign: 'center', fontWeight: 'bold' }}>合计</div>
        //         </Table.Summary.Cell>
        //         <Table.Summary.Cell index={2}>
        //           <Text style={{ fontWeight: 'bold' }}>
        //             {parseFloat(totalDrugTarget.toFixed(6))}
        //           </Text>
        //         </Table.Summary.Cell>
        //         <Table.Summary.Cell index={3}>
        //           <Text style={{ fontWeight: 'bold' }}>
        //             {parseFloat(totalDrugActual.toFixed(6))}
        //           </Text>
        //         </Table.Summary.Cell>
        //         <Table.Summary.Cell index={4}>
        //           <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalDrugVs.toFixed(6))}</Text>
        //         </Table.Summary.Cell>
        //         <Table.Summary.Cell index={5}>
        //           <Text style={{ fontWeight: 'bold' }}>
        //             {parseFloat(totalAmountTarget.toFixed(6))}
        //           </Text>
        //         </Table.Summary.Cell>
        //         <Table.Summary.Cell index={6}>
        //           <Text style={{ fontWeight: 'bold' }}>
        //             {parseFloat(totalAmountActual.toFixed(6))}
        //           </Text>
        //         </Table.Summary.Cell>
        //         <Table.Summary.Cell index={7}>
        //           <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalAmountVs.toFixed(6))}</Text>
        //         </Table.Summary.Cell>
        //         <Table.Summary.Cell index={8}>
        //           <Text style={{ fontWeight: 'bold' }}>
        //             {parseFloat(totalAmountActualWow.toFixed(6))}
        //           </Text>
        //         </Table.Summary.Cell>
        //       </Table.Summary.Row>
        //     </>
        //   );
        // }}
        scroll={{
          x: 'max-content'
          // y: 450
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={false}
      />
      {/* end表格 */}
    </>
  );
};

export default Page;
